<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>snake html</title>
	<style>
		.box{
			border: 1px solid #ccc;
/*			width: 40px; 
			height: 40px;*/
			float: left;
			display: block;
			box-sizing: border-box;
		}
	</style>
	<script>
		(function(win) {
			function _box(x, y, dom) {
				this.x = x;
				this.y = y;
				this.dom = dom;

				this.isActvied = false;
				this.isHead = false;

				this.draw = function() {
					if(this.isActvied) {
						this.dom.style.backgroundColor = "red";
						if(this.isHead) {
							this.dom.style.backgroundColor = "blue";
						}
					} else {
						this.dom.style.backgroundColor = "";
					}
				}
			}

			var _snake = function() {
				this.width = 800;
				this.height = 400;
				this.box_width = 40;
				this.box_height = 40;
				this.boxes_matrix = [];
				this.boxes = [];
				this.snake = [];
			}

			var proto = _snake.prototype;

			proto.init = function() {
				var xnum = this.width / this.box_width;
				var ynum = this.height / this.box_height;
				console.log(xnum, ynum);
				this.xnum = xnum;
				this.ynum = ynum;

				for(var i = 0; i < ynum; i++) {
					var row = [];
					this.boxes_matrix.push(row);
					for(var j = 0; j < xnum; j++) {
						var dom = document.createElement("div");
						dom.className = "box";
						dom.style.width = this.box_width + "px";
						dom.style.height = this.box_height + "px";
						dom.innerHTML = i + "," + j;
						var box = new _box(i, j, dom);
						row.push(box);
						this.boxes.push(box);
					}
				}
				
				this.draw_panel();

				this.init_snake();
			}

			proto.init_snake = function() {
				// console.log(this.boxes_matrix.length);
				var x = Math.ceil(Math.random() * this.xnum - 1);
				var y = Math.ceil(Math.random() * this.ynum - 1);

				this.snake.push({x: x, y: y});
				console.log(this.snake);
				for(var i = 0; i < 2; i++) {
					var n = x + 1;
					// if(n > this.boxes_matrix.)
				}
				
				// var head_box = this.boxes_matrix[x][y];
				// head_box.isHead = true;
				// head_box.isActvied = true;
				// head_box.draw();
			}

			proto.draw_panel = function() {
				this.container = document.querySelector("#container");
				this.container.style.cssText = "border:1px solid #ccc; margin:10px auto;";
				this.container.style.height = this.height + "px";
				this.container.style.width = this.width + "px";


				var f = document.createDocumentFragment();
				// console.log(f);
				for(var i = 0; i < this.boxes.length; i++) {
					// console.log(this.boxes[i].dom);
					f.appendChild(this.boxes[i].dom);
				}

				this.container.appendChild(f);

			}

			win.Snake = _snake;
		})(window);

		window.onload = function() {
			var snake = new Snake();
			snake.init();
		}
	</script>
</head>
<body>
	
	<div id="container"></div>

</body>
</html>